package com.desire.homework;

import java.util.*;

/**
 * 将一个字符串数组进行分组输出，每组中的字符串都由相同的字符组成。
 * 举个例子：输入[“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
 * 输出[[“ate”,”eat”,”tea”],[“nat”,”tan”],[“bat”]]
 *
 * @author desire
 */
public class _18_字符串相同的分组__面试题 {

    public static void main(String[] args) {
        String[] strs = {"ate", "tae", "tan", "ant", "eat", "bat"};
        System.out.println(grouper(strs));
    }

    public static List<List<String>> grouper(String[] strs) {
        if (strs == null || strs.length == 0) {
            return new ArrayList<>();
        }
        // 首先根据单词的首字母进行排序
        Arrays.sort(strs);
        //创建一个二维 map集合,(去重)
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            // 将每个单词转换成字符数组
            char[] c = str.toCharArray();
            // 将单词字母进行排序
            Arrays.sort(c);
            // String.valueOf() 由基本数据型态转换成 String ** 将排好序的单词再次转换成字符串
            String sortedStr = String.valueOf(c);
            // .containsKey() 方法——判断是否包含指定的键名
            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            map.get(sortedStr).add(str);
        }
        return new ArrayList<>(map.values());
    }

    /*public static void main(String[] args) {
        String[] s = new String[]{"age", "gae", "name", "nmae", "mnae", "main", "mian", "keli"};
        System.out.println(Arrays.toString(s));
        for (int i = 0; i < s.length; i++) {
            // 存放第一个数
            String before = s[i];
            for (int j = i + 1; j < s.length; j++) {
                String after = s[j];
                if (isSameString(before, after)) {
                    s[i] = s[i] + "-" + s[j];
                    s[j] = "";
                }
            }
        }
        System.out.println(Arrays.deepToString(s));

        String temp = "";
        for (String s1 : s) {
            if ("".equals(s1) || "-".equals(s1)) {
                continue;
            }
            temp = temp + "," + s1;
        }
        String[] oo = temp.substring(1).split(",");
        String result = "";
        String re = "\",\"";
        for (String s1 : oo) {
            *//*s1.substring(1).replace("-",re);*//*
            result = "[\"" + s1.replace("-", re) + "\"]" + ",";
            System.out.print(result);
        }

    }


    public static boolean isSameString(String before, String after) {
        boolean flag = false;
        if (before.length() == after.length()) {
            // 转换成字符数组 然后按字母前后顺序排好
            char[] charBefore = before.toCharArray();
            Arrays.sort(charBefore);
            char[] charAfter = after.toCharArray();
            Arrays.sort(charAfter);
            // 然后进行挨个比较
            flag = new String(charBefore).equals(new String(charAfter));
        }
        return flag;
    }*/
}
